package cn.cxj.basic.service.impl;

import cn.cxj.basic.constant.BaseConstants;
import cn.cxj.basic.exception.BusinessException;
import cn.cxj.basic.service.IVerifyCodeService;
import cn.cxj.basic.util.StrUtils;
import cn.cxj.user.domain.User;
import cn.cxj.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendSmsCode(Map<String, String> params) {
        String phone = params.get("phone");
        String type = params.get("type");
        // 校验
        // 判断手机号是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)) {
            throw new BusinessException("手机号不能为空!");
        }
        // 判断验证码是否有效(3分钟) key=业务键+手机号 value=验证码+时间戳
        String Bussinesskey = "";
        if ("register".equals(type)) {
            // 判断手机号是否已经注册
            User user = userMapper.loadByPhone(phone);
            if (user != null) {
                throw new BusinessException("用户已经存在,请直接登录!");
            }
            Bussinesskey = BaseConstants.BUSINESS_REGISTER_PREFIX + phone;
        }else if("binder".equals(type)){
            Bussinesskey = BaseConstants.BUSINESS_BINDER_PREFIX + phone;
        }
        sendCode(Bussinesskey);
    }

    public void sendCode(String Bussinesskey){
        String key = Bussinesskey;
        Object codeValueTemp = redisTemplate.opsForValue().get(key);
        // 验证码有效
        String code = "";
        if (codeValueTemp != null) {
            // 判断是否已经过了1分钟重发时间
            Long oldTime = Long.valueOf(((String) codeValueTemp).split(":")[1]);
            if (System.currentTimeMillis() - oldTime <= 1 * 60 * 1000) {
                // 没过1分钟,恶意攻击
                throw new BusinessException("就这啊?啊对对对!");
            }
            // 过了1分钟,小于三分之,查询redis获取验证码
            code = ((String) codeValueTemp).split(":")[0];
        }else{
            // 验证码已经过期或者是新用户第1次点击,获取新的验证码
            code = StrUtils.getComplexRandomString(4);
        }
        // 将验证码保存到redis并设置过期时间为三分钟
        String codeVal = code + ":" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(
                key,
                codeVal,
                3,
                TimeUnit.MINUTES);
        // 通过Sms工具类发送验证码
//        SmsUtil.sendSms(phone,"您的验证码是:" + code + ",请在三分钟内使用!");
        System.out.println("您的验证码是:" + code + ",请在三分钟内使用!");
    }
}
